﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
using MyTcpIp.tcpAsynService;
using MyTcpIp.netPacket;
using MyTcpIp.displacement;
using MyTcpIp.configuration;
using MyTcpIp.acceleration;
using MyTcpIp.speedData;
using MyTcpIp.speedRealTVol;
using MyTcpIp.slowSignal;

namespace MyTcpIp
{
    public class ClientManager
    {
        public delegate void GetDispalcementHandler(DisplacementData data);
        public delegate void GetAccDataHandler(AccData data);
        public delegate void GetStringHandler(string msg);
        public delegate void GetConfigHandler(ACQParametersConfig acqConfig);
        public delegate void GetSpeedHandler(SpeedData data);
        public delegate void GetSpeedVolHandler(SpeedRealTVol data);
        public delegate void GetSlowSignalHandler(SlowSignal slowSignal);
        public delegate void GetMachineTimeHandler(MachineTime machineTime);
        //public delegate void GetNetPacketHandler(NetPacket packet);


        //事件
        public event GetDispalcementHandler GetDisplacement;
        public event GetStringHandler GetString;
        public event GetConfigHandler GetConfig;
        public event GetAccDataHandler GetAccData;
        public event GetSpeedHandler GetSpeed;
        public event GetSpeedVolHandler GetSpeedVol;
        public event GetSlowSignalHandler GetSlowSignal;
        public event GetMachineTimeHandler GetMachineTime;
        //public event GetNetPacketHandler GetNetPacket;

        //public event ReceiveMsgHandler update;
        //保存连接成功的client
        //用于管理客户端
        //问题：管理客户端应该放在Form，在MyTCPIP中只是一个Client
        private List<ClientPack> client_list = new List<ClientPack>();


        public List<bool> getConnnectStatus()
        {
            List<bool> state = new List<bool>();
            int n = client_list.Count;
            for(int i=0;i<n;i++)
            {
                state.Add(client_list[i].isConnected());
            }
            return state;
        }
        public ClientManager()
        {

        }

        public void classificattion(NetPacket packet)
        {
            //GetNetPacket(packet);
            switch (packet.NetPacketHead.PacketType)
            {
                case packetType.PacketType.STRING:
                    //Console.WriteLine(packet.Data.ToString());
                    GetString(packet.DataPacket.ToString());
                    if (packet.DataPacket.ToString().Contains("HeartBeat"))
                    {
                        //HeatBeat = HeatBeat + 1;
                        //SendString("HeartBeatMaster");
                        //Console.WriteLine(this.Master.id+"心跳");
                        //  this.RecieveListString.Add(packet.Data.ToString());
                    }
                    //else if (packet.DataPacket.ToString().Contains("ACQSET"))
                    //{
                    //    Mdl_Class.ACQSet = packet.Data.ToString();
                    //}
                    //else if (packet.Data.ToString().Contains("CHANNELSET"))
                    //{
                    //    Mdl_Class.ChannelSet = packet.Data.ToString();
                    //}
                    //else
                    //{
                    //    this.RecieveListString.Add(packet.Data.ToString());
                    //}
                    //if (packet.Data.ToString().Contains("WillDisConncet"))
                    //{
                    //    //写入日志
                    //    // 重连
                    //    (this.tcpPacketServiceSvr as Cls_NetPacketTcpAsynService).ClientNormalExitFlag = false;
                    //}

                    break;
                case packetType.PacketType.ACQParametersConfig:
                    ACQParametersConfig acq = (ACQParametersConfig)packet.DataPacket;
                    GetConfig(acq);

                    break;
                //case PacketType.ChannelConfig:
                //    ChannelConfig chc = (ChannelConfig)packet.Data;
                //    RecieveListChannelConfig.Add(chc);
                //    break;

                //case PacketType.TestPointConfig:
                //    TestPointConfig ss = (TestPointConfig)packet.Data;
                //    RecieveListTPC.Add(ss);
                //    break;

                //case PacketType.SpeedConfig:
                //    SpeedConfig bb = (SpeedConfig)packet.Data;
                //    RecieveListSC.Add(bb);
                //    break;
                case packetType.PacketType.DisplacementPacket:
                    DisplacementData dpt = (DisplacementData)packet.DataPacket;
                    GetDisplacement(dpt);

                    break;
                case packetType.PacketType.AccelerationPacket:
                    AccData acc = (AccData)packet.DataPacket;
                    GetAccData(acc);

                    break;
                case packetType.PacketType.SpeedPacket:
                    SpeedData speed = (SpeedData)packet.DataPacket;
                    GetSpeed(speed);

                    break;
                case packetType.PacketType.SpeedVoltagePacket:
                    SpeedRealTVol speedVol = (SpeedRealTVol)packet.DataPacket;
                    GetSpeedVol(speedVol);

                    break;
                case packetType.PacketType.SlowSignalPacket:
                    SlowSignal slowSignal = (SlowSignal)packet.DataPacket;
                    GetSlowSignal(slowSignal);

                    break;
                case packetType.PacketType.TimeSetting:
                    MachineTime machineTime = (MachineTime)packet.DataPacket;
                    GetMachineTime(machineTime);

                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 针对需要连接多个下位机的情况，用于判断目标端口是否已经成功连接
        /// </summary>
        /// <param name="serverIP"></param>
        /// <param name="port"></param>
        /// <returns>返回true表示已连接</returns>
        private bool isConnected(string serverIP, int port)
        {
            //遍历client_list即可
            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serverIP"></param>
        /// <param name="port"></param>
        /// <returns>返回true表示连接成功</returns>
        //private Socket _clientSocket = null;
        public bool Connect2Server(string serverIP,int port)
        {
            try
        {
                IPAddress ip = IPAddress.Parse(serverIP);
                Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.Connect(new IPEndPoint(ip, port)); //配置服务器IP与端口   
                //_clientSocket =Connect2Server(serverIP, port);
              
                if (_clientSocket.Connected)
                {
                    ClientPack cp = new ClientPack();
                    cp.client = _clientSocket;

                    //启动异步网络服务
                    NetworkStream netStream = new NetworkStream(_clientSocket);                                  

                    cp.TcpService = new TcpAsynService(netStream);
                    cp.TcpService.ReceivePacket();

                    //在AsynService类中处理接收到的数据，包括反序列化、提取包头、包体
                    //cp.AsynService.OnReceiveMsg += update;
                    cp.TcpService.OnReceivedPacket += classificattion;
                    //cp.AsynService.ReceivePacket();

                    //AsynService类接收到一个完整数据包后，触发事件OnReceive
                    //但是由于结构体的动态配置，服务类需要首先判断能否解析数据
                    //AsynService.OnReceivedPacket+=
                    client_list.Add(cp);
                }
                else
                {
                    //_clientSocket = null;

                    return false;
                }

                return _clientSocket.Connected;
            }
            catch (Exception ex)
            {
                return false;
            }
           
        }

        //private Socket Connect2Server(string serverIP, int port)
        //{
        //    IPAddress ip = IPAddress.Parse(serverIP);
        //    Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    clientSocket.Connect(new IPEndPoint(ip, port)); //配置服务器IP与端口    
        //    return clientSocket;

        //}

        /// <summary>
        /// 获取完整数据包后，执行这个函数
        /// </summary>
        /// <param name="packet"></param>
        public void PacketUpdate1(NetPacket packet)
        {
            //解析

            //packetupdate(packet);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="IP">向该IP发送信息</param>
        public void sendString(string IP, string message)
        {
            //搜索client_list，找到连接目标IP的socket
            //略。。。。
            //使用李福安的程序发送原本的结构体            
            //client_list[0].AsynService.SendText("handshark;Monitor");
            //client_list[0].AsynService.SendText("StartData");
            //使用自定义的函数发送新内容，具体内容未写
            //client_list[0].AsynService.Send();
            if(client_list[0].isConnected())
            {
                client_list[0].TcpService.SendText(message);
            }
            else
            {
                EndPoint ep = client_list[0].client.RemoteEndPoint;
                client_list[0].client.Connect(ep);

                NetworkStream netStream = new NetworkStream(client_list[0].client);
                client_list[0].TcpService = new TcpAsynService(netStream);
                client_list[0].TcpService.ReceivePacket();

                //在AsynService类中处理接收到的数据，包括反序列化、提取包头、包体
                //cp.AsynService.OnReceiveMsg += update;
                client_list[0].TcpService.OnReceivedPacket -= classificattion;
                client_list[0].TcpService.OnReceivedPacket += classificattion;

                client_list[0].TcpService.SendText(message);
            }

            //client_list[0].TcpService.
        }

        public void SendNetPacket(string IP, MyTcpIp.netPacket.NetPacket netPacket)
        {
            try
            {
                //client_list[0].AsynService.SendPacket(netPacket);
                client_list[0].TcpService.SendPacket(netPacket);
            }
            catch(Exception ex)
            {
                
            }
        }

    }


    class ClientPack
    {
        public ClientPack()
        {

        }
        private Socket _client = null;
        public Socket client
        {
            set { _client = value; }
            get { return _client; }
        }

        public TcpAsynService TcpService { get; set; }

        public bool isConnected()
        {
            //return client.Connected;
            return !client.Poll(10, SelectMode.SelectRead);

            //Socket s = new Socket(..);
            //if (s.Poll(-1, SelectMode.SelectRead))
            //{
            //    int nRead = s.Receive();
            //    if (nRead == 0)
            //    {
            //        //socket连接已断开
            //    }
            //}
        }
        //private Cls_NetPacketTcpAsynService _AsynService = null;
        //public Cls_NetPacketTcpAsynService AsynService
        //{
        //    set { _AsynService = value; }
        //    get { return _AsynService; }
        //}
        //public void ReConnect()
        //{
        //    if (_client != null)
        //    {
        //        EndPoint ipep = _client.RemoteEndPoint;
        //        _client.Connect(ipep); //配置服务器IP与端口   

        //        if (_client.Connected)
        //        {

        //        }
        //    }
        //}
    }
}
